package com.bdsy.business.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.bdsy.common.utils.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.bdsy.api.annotation.IgnoreAuth;
import com.bdsy.business.model.AuctionShop;
import com.bdsy.business.model.ScaveRecord;
import com.bdsy.business.model.ShopImage;
import com.bdsy.business.model.ShopSellInfo;
import com.bdsy.business.model.ShopTrail;
import com.bdsy.business.model.ShopType;
import com.bdsy.business.service.AuctionShopService;
import com.bdsy.business.service.ScaveRecordService;
import com.bdsy.business.service.ShopImageService;
import com.bdsy.business.service.ShopSellInfoService;
import com.bdsy.business.service.ShopTrailService;
import com.bdsy.business.service.ShopTypeService;
import com.bdsy.common.annotation.Json;

import com.bdsy.system.annotation.SysLog;
import com.bdsy.system.model.User;

@Controller
@RequestMapping(value = {"${web.adminPath}", "${web.appPath}"})
public class ShopSellInfoController {

	@Autowired
	ShopSellInfoService shopSellInfoService;
	
	@Autowired
	ShopImageService shopImageService;
	
	@Autowired
	ScaveRecordService scaveRecordService;
	
	@Autowired
	ShopTrailService shopTrailService;
	
	@Autowired
	ShopTypeService shopTypeService;
	
	@Autowired
	private AuctionShopService auctionShopService;
	
	/**
	 * 查询出售商品信息
	 */
	@RequestMapping(value = "shopSellInfoList")
	@ResponseBody
	public Object shopSellInfoList() {
		Map<String,Object> map = new LinkedHashMap<>();
		
		@SuppressWarnings("rawtypes")
//		List<ShopSellInfo> shopSellInfoList = shopSellInfoService.selectShopInfo();
		List<Map> shopSellInfoList = shopSellInfoService.selectShopSellInfo();
		System.out.println(shopSellInfoList);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", shopSellInfoList);
		return map;
	}
	
	
	/**
	 * 查询租赁商品信息
	 */
	@RequestMapping(value = "zlshopSellInfoList")
	@ResponseBody
	public Object zlshopSellInfoList() {
		Map<String,Object> map = new LinkedHashMap<>();
		
		@SuppressWarnings("rawtypes")
		List<Map> zlshopSellInfoList = shopSellInfoService.selectzlShopSellInfo();
		System.out.println(zlshopSellInfoList);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", zlshopSellInfoList);
		return map;
	}
	
	
	/**
	 * 根据商品类型查询出售商品信息
	 */
	@RequestMapping(value = "shopSellInfoListByTypeId")
	@ResponseBody
	public Object shopSellInfoListByTypeId(Integer shopTypeId) {
		Map<String,Object> map = new LinkedHashMap<>();
		
		@SuppressWarnings("rawtypes")
		List<Map> shopSellInfoList = shopSellInfoService.shopSellInfoListByTypeId(shopTypeId);
		int count = shopSellInfoService.count(shopTypeId);
		map.put("code", 200);
		map.put("total", count);
		map.put("msg", "success");
		map.put("data", shopSellInfoList);
		return map;
	}
	
	
	/**
	 * 根据商品类型查询租赁商品信息
	 */
	@RequestMapping(value = "shopzlSellInfoListByTypeId")
	@ResponseBody
	public Object shopzlSellInfoListByTypeId(Integer shopTypeId) {
		Map<String,Object> map = new LinkedHashMap<>();
		
		@SuppressWarnings("rawtypes")
		List<Map> shopzlSellInfoList = shopSellInfoService.shopzlSellInfoListByTypeId(shopTypeId);
		int count = shopSellInfoService.zcount(shopTypeId);
		map.put("code", 200);
		map.put("total", count);
		map.put("msg", "success");
		map.put("data", shopzlSellInfoList);
		return map;
	}
	
	
	
	/**
	 * 根据id查询出售商品信息
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "shopList")
	public Object shopList(String userId) {
		@SuppressWarnings("rawtypes")
		List<Map> shopList = shopSellInfoService.selectShopSellInfoById(userId);
		System.out.println(shopList);
		Map<String,Object> map = new LinkedHashMap<>();
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", shopList);
		return map;
	}
	
	
	/**
	 * 根据id查询租赁商品信息
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "zlshopList")
	public Object zlshopList(String userId) {
		@SuppressWarnings("rawtypes")
		List<Map> zlshopList = shopSellInfoService.selectzlShopSellInfoById(userId);
		System.out.println(zlshopList);
		Map<String,Object> map = new LinkedHashMap<>();
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", zlshopList);
		return map;
	}
	
	
	@RequestMapping(value = "upload")
	public String shopUpload() {
		return "admin/business/upload";
	}
	
	@RequestMapping(value = "emupload")
	public String emupload() {
		return "admin/business/umeditor";
	}
	

	
	/**
	 * 新增出售商品信息
	 * @param
	 * @author MING
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @date 2017年12月29日 下午4:07:54
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "addShopSellInfo")
	public Object addShopSellInfo(MultipartFile file,ShopSellInfo shopSellInfo,ShopImage shopImage,ShopTrail shopTrail,String userId,HttpServletRequest request,String icdn,AuctionShop auctionShop){
		 
		// 根据 icdn 查询  shopId
		@SuppressWarnings("rawtypes")
		List<Map> shop = shopSellInfoService.shopSellInfoByIcdn(icdn);
		int shopId = 0;
		for (int i = 0; i < shop.size(); i++) {
			Map<String,Object> map = shop.get(0);
		    shopId = (int) map.get("shop_id");
		}
//		System.out.println(shopId);
		shopSellInfo.setShopId(shopId);
		shopSellInfo.setUserId(userId);
		shopSellInfo.setAddTime(DateUtil.getCurrentDate());
		boolean result = shopSellInfoService.update(shopSellInfo);
		
		//添加轨迹信息
		shopTrail.setShopId(shopId);
		shopTrail.setAddUserId(userId);
		boolean result2 = shopTrailService.add(shopTrail);
		//添加商品图片
		shopImage.setShopId(shopId);
		boolean result3 = shopImageService.addImage(shopImage, file);	
		
		// 如果是竞拍 添加竞拍信息
		if(shopSellInfo.getsStatus() == 2) {
			auctionShop.setShopId(shopId);
			auctionShop.setAuctionStatus(0);
			auctionShop.setIncrePrice(shopSellInfo.getShopPrice());
			auctionShopService.add(auctionShop);
		}
		

		if (result && result2 && result3) {
			return Result.ok("addSuccess");
		} else {
			return Result.error("addFail");
		}
	}
	 	
	
	//生成二维码静态方法  //路径有问题
	public void icodeByShopIds(HttpServletRequest request,Integer shopId,ShopImage shopImage){
		 
        try {   // 根据商品id生成二维码
			String rscode = QRCodeUtil.icodes(request,shopId.toString(), null, null,true);
					// 把生成的二维码存到数据库里面 修改图片表
			 System.out.println(rscode+"---------");
			 shopImage.setQrcodeUrl(rscode);
			 shopImage.setShopId(shopId);
			 shopImageService.update(shopImage);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}
	
	
	
	
	/**
	 * 根据商品ID 生成二维码
	 */
	@Json
	@RequestMapping(value = "icodeByShopId")
	public Object icodeByShopId(HttpServletRequest request,Integer shopId,ShopImage shopImage){
		 
		boolean result = false;
        try {   // 根据商品id生成二维码
			String rscode = QRCodeUtil.icodes(request,shopId.toString(), null, null,true);
			// 把生成的二维码存到数据库里面 修改图片表
			 System.out.println(rscode+"---------");
			 shopImage.setQrcodeUrl(rscode);
			 shopImage.setShopId(shopId);
			 result = shopImageService.update(shopImage);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        if (result) {
			return Result.ok("QRCodeSuccess");
		} else {
			return Result.error("QRCodeFail");
		}
        
	}
	
	
	/**
	 * 根据 商品ID查询商品信息
	 */
	@Json
	@RequestMapping(value = "shopSellInfoByShopId")
	public Object shopSellInfoByShopId(HttpServletRequest request,Integer shopId,String userId){
		Map<String,Object> map = new LinkedHashMap<>();
		@SuppressWarnings("rawtypes")
        List<Map> shopInfoList= shopSellInfoService.selectShopSellInfoByShopId(shopId);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", shopInfoList);
		return map;
	}
	
	
	
	/**
	 * 根据 生成二维码（Icdn） 查询商品信息 并添加 扫描记录
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "shopSellInfoByIcdn")
	public Object shopSellInfoByIcdn(HttpServletRequest request,String icdn,ScaveRecord scaveRecord,String userId){
		
		Map<String,Object> map = new LinkedHashMap<>();
		@SuppressWarnings("rawtypes")
//        List<Map> shopInfoList= shopSellInfoService.selectShopSellInfoByShopId(shopId);
		List<Map> shopInfoList= shopSellInfoService.selectShopSellInfoByIcdn(icdn);
		Integer shopId = null;
		for (int i = 0; i < shopInfoList.size(); i++) {
			shopId = (Integer) shopInfoList.get(0).get("shop_id");
		}
		scaveRecord.setShopId(shopId);
		scaveRecord.setUserId(userId);
		scaveRecordService.insert(scaveRecord);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", shopInfoList);
		return map;
	}
	
	
	/**
	 * 根据 生成二维码（商品ID） 查询商品信息
	 */
	@Json
	@RequestMapping(value = "sellInfoByShopId")
	public Object sellInfoByShopId(HttpServletRequest request,Integer shopId){
		
		Map<String,Object> map = new LinkedHashMap<>();
		@SuppressWarnings("rawtypes")
        List<Map> shopInfoList= shopSellInfoService.selectShopSellInfoByShopId(shopId);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", shopInfoList);
		return map;
	}
	
	
	
	/*@Json
	@SysLog("新增出售商品信息") // 图片上传
	@RequestMapping(value = "saveShopSellInfo")
	public Object saveShopSellInfo(ShopSellInfo shopSellInfo,ShopImage shopImage,HttpServletRequest request) throws Exception, IOException {
		int number = (int)((Math.random()*9+1)*10000000);
		shopSellInfo.setShopId(number);
		boolean result = shopSellInfoService.add(shopSellInfo);
		
		 //保存数据库的路径  
	      String sqlPath = null;   
	      //定义文件保存的本地路径  
//	      String localPath="H:\\File\\";  
	      //定义 文件名  
	      String filename=null;    
	      if(!shopImage.getFile().isEmpty()){    
	          //生成uuid作为文件名称    
	          String uuid = UUID.randomUUID().toString().replaceAll("-","");    
	          //获得文件类型（可以判断如果不是图片，禁止上传）    
	          String contentType=shopImage.getFile().getContentType();    
	          //获得文件后缀名   
	          String suffixName=contentType.substring(contentType.indexOf("/")+1);  
	          //得到 文件名  
	          filename=uuid+"."+suffixName;   
	          System.out.println(filename);  
	          String localPath = request.getSession().getServletContext().getRealPath("/images"); 
	          //文件保存路径  
	          File dir = new File(localPath,filename);  
	          if(!dir.exists()){  
	        	  dir.mkdirs();  
	          }   
	          shopImage.getFile().transferTo(dir); 
	         //把图片的相对路径保存至数据库  
	          sqlPath = "/images/"+filename;  
	          System.out.println(sqlPath); 
	      }   
			shopImage.setImageUrl(sqlPath);
			shopImageService.add(shopImage);
	      
		if (result) {
			return Result.ok("添加成功");
		} else {
			return Result.error("添加失败");
		}
	}
	*/
	
	/**
	 * 商品上下架
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "updateShopStatus")
	public Object updateShopStatus(ShopSellInfo shopSellInfo){
        boolean result = shopSellInfoService.updateShopStatus(shopSellInfo);
		if (result) {
			if(shopSellInfo.getStandDown() == 1){
				return Result.ok("下架成功");
			}
			return Result.ok("上架成功");
		}else{
			if(shopSellInfo.getStandDown() == 0){
				return Result.ok("上架失败");
			}
			return Result.error("下架失败");
		}
	}
	
	/**
	 * 根据用户ID查询商品下架信息 
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "selectShopSellInfoByIdStand")
	public Object selectShopSellInfoByIdStand(String userId,Integer sStatus){
		Map<String,Object> map = new LinkedHashMap<>();
		@SuppressWarnings("rawtypes")
		List<Map> standShopSellInfoList = shopSellInfoService.selectShopSellInfoByIdStand(userId,sStatus);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", standShopSellInfoList);
		return map;
	}
	
	
	/**
	 * 根据商品ID查询细节图
	 */
	@Json
	@RequestMapping(value = "imageInfoById")
	public Object imageInfoById(int shopId){
		Map<String,Object> map = new LinkedHashMap<>();
		@SuppressWarnings("rawtypes")
		List<Map> imageInfo = shopSellInfoService.imageInfoById(shopId);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", imageInfo);
		return map;
	}
	
	
// 后台 ----------------------------------------------------------------------
	
	/**
	 * 商品信息
	 * @param model
	 * @return
	 * @author MING
	 * @date 2018年1月22日 下午5:24:43
	 */
	@RequestMapping(value = "shop")
	public String shop(Model model) {
//		List<Map> shopSellInfoList = shopSellInfoService.selectShopSellInfoByIdStatus(userId,status);
		List<ShopType> shopTypeInfo = shopTypeService.shopTypeInfo();
	/*	if (!shopSellInfoList.isEmpty()) {
			model.addAttribute("shopSellInfoList", shopSellInfoList);
		}*/
		if (!shopTypeInfo.isEmpty()) {
			model.addAttribute("shopTypeInfo", shopTypeInfo);
		}
		return "admin/business/shop";
	}
	
	
	@RequestMapping(value = "selectShopSellInfoByIdStatus")
	@ResponseBody
	public Object selectShopSellInfoByIdStatus(HttpServletRequest request,Model model,@Param(value = "userId")String userId,@Param(value = "status")int status,int standDown) {
		User user = (User) request.getSession().getAttribute("user");
		userId = user.getUserId();
//		userId = "R2fYuQC6";
		List<Map> shopSellInfoList = shopSellInfoService.selectShopSellInfoByIdStatus(userId,status,standDown);
		return shopSellInfoList;
	}

	@RequestMapping(value = "selectShopSellInfoByuserIdStatus")
	@ResponseBody
	public Object selectShopSellInfoByuserIdStatus(HttpServletRequest request,Model model,@Param(value = "userId")String userId,@Param(value = "status")int status) {
		User user = (User) request.getSession().getAttribute("user");
		userId = user.getUserId();
		List<Map> shopSellInfoList = shopSellInfoService.selectShopSellInfoByuserIdStatus(userId,status);
		return shopSellInfoList;
	}
	
	
	@RequestMapping(value = "shopListByTime")
	@ResponseBody
	public Object shopListByTime(HttpServletRequest request,String fromDate,String toDate,int sStatus) {
		User user = (User) request.getSession().getAttribute("user");
		String userId = user.getUserId();
		List<Map> shopList = shopSellInfoService.shopListByTime(fromDate, toDate, userId, sStatus);
		return shopList;
	}
	
	
	
	@Json
	@SysLog("根据 商品ID删除商品信息 ")
	@RequestMapping(value = "deleteShop")
	public Object deleteShop(String pIds) {
		List<String> list = JSON.parseArray(pIds, String.class);
		boolean result = shopSellInfoService.delete(list);
		if (result) {
    		return Result.ok("删除成功");
		}else{
			return Result.error("删除失败");
		}
	}
	
	@Json
	@SysLog("根据 商品ID查询商品信息 ")
	@RequestMapping(value = "shopSellInfoById")
	public Object shopSellInfoById(HttpServletRequest request,Integer shopId){
		@SuppressWarnings("rawtypes")
        List<Map> shopInfoList= shopSellInfoService.selectShopSellInfoByShopId(shopId);
		return shopInfoList;
	}
	
	@Json
	@SysLog("根据 商品ID修改商品信息 ")
	@RequestMapping(value = "updateShopSellInfoById")
	public Object updateShopSellInfoById(ShopSellInfo shopSellInfo){
        boolean result = shopSellInfoService.update(shopSellInfo);
		if (result) {
    		return Result.ok("修改成功");
		}else{
			return Result.error("修改失败");
		}
	}
	
	
	@Json
	@SysLog("新增出售商品信息")
	@RequestMapping(value = "addShopSellInfos")
	public Object addShopSellInfos(MultipartFile file,ShopSellInfo shopSellInfo,ShopImage shopImage,ShopTrail shopTrail,AuctionShop auctionShop,HttpServletRequest request){
		 
		User user = (User)request.getSession().getAttribute("user");
//		System.out.println(user);
		int number = (int)((Math.random()*9+1)*10000000);
		shopSellInfo.setShopId(number);
		shopSellInfo.setUserId(user.getUserId());
		
		//暂时使用测试icdn
		  //调用IcdnUtils
		  String icdn = IcdnUtils.getIcdns();
		  shopSellInfo.setIcdn(icdn);
		//添加商品
		boolean result = shopSellInfoService.add(shopSellInfo);
		//添加轨迹信息
		shopTrail.setShopId(number);
		shopTrail.setAddUserId(user.getUserId());
		boolean result2 = shopTrailService.add(shopTrail);
		//添加商品图片
		shopImage.setShopId(number);
		boolean result3 = shopImageService.add(shopImage,file,request);
		
		//生成二维码
//		icodeByShopIds(request, number, shopImage);
		
		//暂时使用测试icdn
		  //调用IcdnUtils  
//		  String icdn = IcdnUtils.getIcdns();
//		  String path = "E:\\Program Files\\Apache Software Foundation\\apache-tomcat-8.5.23\\webapps\\adicms_image\\qrimages";
		  String path = "/usr/local/tomcat/webapps/adicms_image/qrimages";
		  String name = new Random().nextInt(99999999)+".jpg";  
	    // 依次为内容(不支持中文),宽,长,中间图标路径,储存路径  
		  //windows
//		  QRUtils.encode(icdn, 512, 512,path+"\\logo.jpg", path+"\\"+name);
		  //linux
		  QRUtils.encode(icdn, 512, 512,path+"/logo.jpg", path+"/"+name);
		  System.out.println("生成成功");
			 shopImage.setQrcodeUrl("/qrimages/"+name);
			 shopImage.setShopId(number);
		  shopImageService.update(shopImage);
		  
		  // 添加竞拍信息
		  auctionShop.setShopId(number);
		  auctionShop.setIncrePrice(shopSellInfo.getShopPrice());
		  auctionShop.setAuctionStatus(0);
		  auctionShopService.add(auctionShop);
		  
		  
		if (result && result2 && result3) {
			return Result.ok("addSuccess");
		} else {
			return Result.error("addFail");
		}
	}
	
	
	@Json
	@SysLog("根据 商品ID查询商品信息 ")
	@RequestMapping(value = "shopInfoByShopId")
	public Object shopInfoByShopId(HttpServletRequest request,Integer shopId){
		Map<String,Object> map = new LinkedHashMap<>();
		@SuppressWarnings("rawtypes")
        List<Map> shopInfoList= shopSellInfoService.selectShopSellInfoByShopId(shopId);
		return shopInfoList;
	}
	
	@Json
	@SysLog("查询所有商品信息")
	@RequestMapping(value = "allShopSellInfo")
	public Object allShopSellInfo() {
		@SuppressWarnings("rawtypes")
		List<Map> allShopList = shopSellInfoService.selectAllShopSellInfo();
		return allShopList;
	}
	
}
